window.onload = function () {

    function arrauto(arr) {
        let arrres = 0
        arr.forEach(function (el, index) {
            arrres += Number(el)
        })

        return arrres
    }

    //页面总计计算方法
    function automatic() {
        let arr = [...$('tbody :checkbox:checked').parents('tr').children('td').children('.qty-next').prev()]
        let arr1 = []
        arr.forEach(function (el) {
            arr1.push(Number($(el).text()));
        })
        let res1 = arrauto(arr1)
        let arr2 = [...$('tbody :checkbox:checked').parents('tr').children('.subtotal').children()]
        let arr3 = []
        arr2.forEach(function (el) {
            arr3.push(Number($(el).text()));
        })
        let res2 = arrauto(arr3)
        $('.settle p').eq(0).children('span').children('em').text(res1)
        $('.pricesum').text(res2.toFixed(2))
    }


    //    全选

    $('#buycarcheckbox').on('click', function () {
        $('tbody :checkbox').prop('checked', $(this).prop('checked'))
        $('#settleall').prop('checked', $(this).prop('checked'))

        automatic()
    })


    $('#settleall').on('click', function () {
        $('tbody :checkbox').prop('checked', $(this).prop('checked'))
        $('#buycarcheckbox').prop('checked', $(this).prop('checked'))

        automatic()
    })



    // 单项选择
    $('#tbd').on('click', ':checkbox', function () {
        let cboxnum = $('tbody :checkbox').length;

        let checkedboxnum = $('tbody :checkbox:checked').length;
        $('#buycarcheckbox').prop('checked', cboxnum === checkedboxnum)
        $('#settleall').prop('checked', cboxnum === checkedboxnum)
        automatic()
    })



    $(function () {

        //页面初始化加载数据
        if (localStorage.getItem("userinfo")) {
            $.ajax({
                url: '/cart/query',
                type: 'get',
                data: {
                    uId: JSON.parse(localStorage.getItem("userinfo"))[0].u_id
                }
            }).then(function (res) {
                if (res.data == '') {
                    $('.conempty').show().nextAll().hide()
                } else {
                    render(res.data)
                    automatic()
                }
            })
        } else {
            console.log('购物车数据加载失败');
            $('.conempty').show().nextAll().hide()
        }

        //数据渲染到页面方法
        function render(list) {
            let strHtml = ``;
            list.forEach(el => {

                let total = Number(el.c_total).toFixed(2)

                strHtml += `<tr data-cid=${el.c_id}>`
                strHtml += `<td class="leftspace"></td>`
                strHtml += `<td class="bar-title"><input type="checkbox" id="" checked></td>`
                strHtml += ` <td class="image"><img src=${el.c_img}></td>`
                strHtml += `<td class="name">${el.c_name}</td>`
                strHtml += `<td class="size">${el.c_size}</td>`
                strHtml += `<td class="price">¥<span>${el.c_price}</span></td>`
                strHtml += `<td class="qty">
                <span class="qty-prev">-</span>
                <span class="qty-inner">${el.c_num}</span>
                <span class="qty-next">+</span>
            </td>`
                strHtml += `<td class="discount">-</td>`
                strHtml += ` <td class="subtotal">¥<span>${total}</span></td>`
                strHtml += `<td class="operate">删除</td>`
                strHtml += `<td class="rightspace"></td>`
                strHtml += `</tr>`
            });

            $('.carlisttab table tbody').append(strHtml)
        }


        //数量减
        $('#tbd').on('click', '.qty-prev', function () {
            let num = $(this).next().text()
            if (num > 1) {
                num--
            }
            $(this).next().text(num)

            let total = $(this).parent().prev().children().text() * num
            $(this).parent().siblings('.subtotal').children().text(total.toFixed(2))
            automatic()
            $.ajax({
                url: '/cart/modify',
                type: 'post',
                data: {
                    cId: $(this).parents('tr').data('cid'),
                    cnum: num
                }
            })


        })


        //数量加
        $('#tbd').on('click', '.qty-next', function () {
            let num = $(this).prev().text()
            num++
            $(this).prev().text(num)

            let total = $(this).parent().prev().children().text() * num
            $(this).parent().siblings('.subtotal').children().text(total.toFixed(2))
            automatic()
            $.ajax({
                url: '/cart/modify',
                type: 'post',
                data: {
                    cId: $(this).parents('tr').data('cid'),
                    cnum: num
                }
            })


        })


        //购物车删除商品
        $('#tbd').on('click', '.operate', function () {
            let cId = $(this).parents('tr').data('cid');
            let self = this

            $.ajax({
                url: '/cart/delete',
                type: 'post',
                data: {
                    cId
                }
            }).done(function (res) {
                layer.msg(res.msg);
                if (res.status == 200) {
                    $(self).parents('tr').remove()
                    automatic()
                }
            })
            if ($('#tbd tr').length <= 2) {
                $('.conempty').show().nextAll().hide()
            }

        })


        //头部欢迎词


        if (localStorage.getItem("userinfo")) {
            let userInfo = JSON.parse(localStorage.getItem("userinfo") || '[]');
            $(".username").html(`${userInfo[0].u_name}!`)
            $('.exit').html(`退出登录`).prop('href', './login.html')
        } else {

            $(".username").html(`欢迎光临凡客诚品`)
        }

        $('.exit').on('click', function () {
            localStorage.clear();
            $(".username").html(`欢迎光临凡客诚品`)
            $('.exit').html(`登录`).prop('href', './login.html')

        })


    })



}